from typing import Dict, Any
import time


from intelli_port.commons.config import load_settings


s = load_settings()


class PaddleASRInferencer:
    def transcribe_wav(self, path: str, lang: str | None = None) -> Dict[str, Any]:
        t0 = time.time()
        try:
            import paddlespeech
            try:
                from paddlespeech.cli.asr import InferTask as ASRTask
                # PaddleSpeech CLI ASR 暂不显式支持 lang 参数；保留以便后端支持时贯通
                _lang = (lang or s.asr_lang or "zh")
                result = ASRTask().infer({'audio_file': path})
                text = result.get('result', '') if isinstance(result, dict) else str(result)
            except Exception:
                text = ""
        except Exception:
            text = ""
        return {"text": text, "path": path, "latency_ms": max(0, (time.time() - t0) * 1000), "lang": (lang or s.asr_lang)}


class PaddleTTSInferencer:
    def synthesize_to_wav(self, text: str, out_path: str, lang: str | None = None, voice: str | None = None) -> Dict[str, Any]:
        t0 = time.time()
        ok = False
        try:
            import paddlespeech
            try:
                from paddlespeech.cli.tts import TTSExecutor
                # PaddleSpeech CLI TTS 暂未公开 voice/lang 参数；保留以便后端扩展
                _voice = (voice or s.tts_voice)
                _lang = (lang or ("zh" if (_voice or "").startswith("zh") else None))
                TTSExecutor().run(text=text, output=out_path)
                ok = True
            except Exception:
                ok = False
        except Exception:
            ok = False
        if not ok:
            try:
                import wave, struct
                framerate = 16000
                duration = 0.2
                amp = 16000
                freq = 440.0
                with wave.open(out_path, 'wb') as w:
                    w.setnchannels(1)
                    w.setsampwidth(2)
                    w.setframerate(framerate)
                    for i in range(int(framerate * duration)):
                        val = int(amp * 0.5 * (i % (framerate // int(freq)) < (framerate // int(freq)) // 2))
                        w.writeframes(struct.pack('<h', val))
                ok = True
            except Exception:
                ok = False
        return {"ok": ok, "path": out_path, "latency_ms": max(0, (time.time() - t0) * 1000), "lang": (lang or None), "voice": (voice or s.tts_voice)}


class PaddleOCRInferencer:
    def scan_image(self, path: str, lang: str | None = None) -> Dict[str, Any]:
        t0 = time.time()
        text = ""
        try:
            from paddleocr import PaddleOCR
            _lang = (lang or s.ocr_lang or 'ch')
            ocr = PaddleOCR(use_angle_cls=True, lang=_lang)
            result = ocr.ocr(path, cls=True)
            parts = []
            for line in result:
                for det in line:
                    parts.append(det[1][0])
            text = " ".join(parts)
        except Exception:
            text = ""
        return {"text": text, "path": path, "latency_ms": max(0, (time.time() - t0) * 1000), "lang": (lang or s.ocr_lang)}